﻿#include "qdownloader.h"

#include <QFile>
#include <QProcess>
#include <QTextStream>
#include <qdesktopservices>

QDownloader::QDownloader(QObject *parent) :
    QObject(parent)
{
    manager = new QNetworkAccessManager;
}

QDownloader::~QDownloader()
{
    manager->deleteLater();
}

void QDownloader::setWhatTodoAfterDownload(int w)
{
    whatTodoAfterDownload = w;
}


void QDownloader::setActualVersion(QString theVersion)
{
    actualVersion = theVersion;
}

void QDownloader::setInputUrlFile(QString s)
{
    inputUrlFile = s;
}
void QDownloader::setOutputFilePath(QString s)
{
    outputFilePath = s;
}

void QDownloader::startDownload()
{
    if (inputUrlFile == "")
    {
        qDebug("Download error : You must set the url file");
        return ;
    }

    if (outputFilePath == "")
    {
        QStringList filePathList = inputUrlFile.split('/');
        QString fileName = filePathList.at(filePathList.count() - 1);

        outputFilePath = QString("/tmp/" + fileName );

#if defined(Q_OS_WIN32) || defined(Q_OS_WIN64)
    outputFilePath = QString(QString(getenv("TMP")) + "/" + fileName );
#endif
}
    qDebug("Starting download file %s",inputUrlFile.toLatin1().data());
    qDebug("Will save file in %s",outputFilePath.toLatin1().data());

    QNetworkRequest request;
    request.setUrl(QUrl(inputUrlFile));
    reply = manager->get(request);

    qFileClass = new QFile;
    qFileClass->setFileName(outputFilePath);
    qFileClass->open(QIODevice::WriteOnly);

    connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(onDownloadProgress(qint64,qint64)));
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onFinished(QNetworkReply*)));
    connect(reply,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    connect(reply,SIGNAL(finished()),this,SLOT(onReplyFinished()));
}

void QDownloader::onDownloadProgress(qint64 bytesRead,qint64 bytesTotal)
{
   // qDebug("Download progress : " + QString::number(bytesRead).toLatin1() +" / "+ QString::number(bytesTotal).toLatin1() + " Bytes");
}

void QDownloader::compareVersionAndStartInstallIfNecessary()
{
    downloadedVersion = QString(byteArrayDownloadedVersion.split('\n').at(0));
    qDebug("Reading version in file %s : VERSION = %s actualVersion = %s", outputFilePath.toLatin1().data(), downloadedVersion.toLatin1().data(), actualVersion.toLatin1().data());

    QString url = "http://kakola.googlecode.com/files/KaKoLa-Setup-0.2.1.exe";
    QDownloader *d = new QDownloader;
    d->setWhatTodoAfterDownload(1);
    d->setInputUrlFile(url);
    d->setOutputFilePath("C:/KaKoLa-Setup-0.2.1.exe");
    d->startDownload();
}

void QDownloader::onFinished(QNetworkReply * reply)
{
    switch(reply->error())
    {
        case QNetworkReply::NoError:
        {
            qDebug("File %s is downloaded successfully.", outputFilePath.toLatin1().data());
            if (whatTodoAfterDownload == 0)
            {
                compareVersionAndStartInstallIfNecessary();
            }
            else
            {
                qDebug("*** Opening %s ", outputFilePath.toLatin1().data());
                QDesktopServices::openUrl(QUrl(outputFilePath));
                QString program = outputFilePath;
                QStringList arguments;

                QProcess *process = new QProcess(this);
                process->startDetached(program, arguments);
            }
        }break;
        default:{
            qDebug(reply->errorString().toLatin1());
        };
    }

    if(qFileClass->isOpen())
    {
        qFileClass->close();
        //qFileClass->deleteLater();
    }
}

void QDownloader::onReadyRead()
{
    if (whatTodoAfterDownload == 0)
        byteArrayDownloadedVersion = reply->readAll();

    qFileClass->write(reply->readAll());
}

void QDownloader::onReplyFinished()
{
    if(qFileClass->isOpen())
    {
        qFileClass->close();
        //qFileClass->deleteLater();
    }
}
